﻿using System;
using System.Text.RegularExpressions;
using Duo1JHttpServer.Framework.Config;
using Duo1JHttpServer.Framework.Model;
using Duo1JHttpServer.Framework.Utils;

namespace Duo1JHttpServer.Framework.Server
{
    public class HtmlHandler
    {
        private static readonly Regex htmlRegex = new Regex(".+\\.html");

        /// <summary>
        /// 处理html获取请求
        /// </summary>
        /// <returns>是否为html获取请求</returns>
        public static bool HandleHtml(RequestModel requestModel)
        {
            bool htmlRequest = htmlRegex.IsMatch(requestModel.RequestUrl);
            
            if (htmlRequest)
            {
                AnalyzeHtmlRequest(requestModel);
            }

            return htmlRequest;
        }

        private static void AnalyzeHtmlRequest(RequestModel requestModel)
        {
            string path = (GlobalDefine.ViewRoot + requestModel.RequestUrl.Replace("/", "\\"));
            ConsoleUtils.WriteBlueLine($"Try get html: {path}");

            byte[] htmlFile = null;
            if ((htmlFile = IOUtils.ReadFileAll(path)) == null)
            {
                ConsoleUtils.WriteRedLine($"Get html failed: {requestModel.RequestUrl}");
                StaticHandler.RequestNotFound(requestModel);
                return;
            }

            StaticHandler.RequestSuccess(requestModel);
            requestModel.OutputWriter.WriteLine(System.Text.Encoding.UTF8.GetString(htmlFile));
        }
    }
}